<template>
  <PageMain>
    <ProTable ref="tableRef" :columns="columns" :init-param="initParam" :request-api="getTableList" border>
      <template #tableHeader="scope">
        <el-button type="primary" size="default" @click="addFn('新建账号')">新建账号</el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="warning" link @click="resetPwdFn(scope.row)">重置密码</el-button>
        <el-button type="warning" link @click="enableFn(scope.row)">{{ scope.row.disabledFlag ? "启用" : "禁用" }}</el-button>
      </template>
    </ProTable>

    <add ref="addRef" @updata="updata" />
  </PageMain>
</template>

<script setup>
import { ElMessage, ElMessageBox } from "element-plus";
import { status } from "@/utils/dict";
import { useHandleData } from "@/hooks/useHandleData";
import add from "./dialog/add.vue";
import api from "@/api";

const tableRef = ref();

// 表格初始参数
const initParam = reactive({
  pageNum: 1,
  pageSize: 10,
});

const getTableList = (params) => {
  return api.post(`/user/admin/queryList`, params, {
    loading: true,
  });
};

// 表格配置项
const columns = ref([
  { label: "账号", prop: "loginName", align: "left" },
  {
    label: "创建时间",
    prop: "createTime",
    align: "left",
  },
  { label: "角色", prop: "roleNameList", align: "left" },
  { label: "状态", prop: "disabledFlag", align: "left", enum: status },
  { prop: "operation", label: "操作", width: "220px", align: "center", fixed: "right" },
]);

// 更新数据
const updata = () => {
  tableRef.value.getTableList();
};

// 新增用户
const addRef = ref();
const addFn = (title, row) => {
  addRef.value.show(title, row);
};

// 启用禁用
const enableFn = async (row) => {
  const text = row.disabledFlag ? "启用" : "禁用";
  await useHandleData(
    () =>
      api.post(
        `/user/admin/updateDisable`,
        {
          id: row.employeeId,
          disabledFlag: !row.disabledFlag,
        },
        { loading: true }
      ),
    `${text}【${row.loginName}】`
  );

  updata();
};

// 重置密码
const resetPwdFn = async (row) => {
  await useHandleData(
    () => api.get(`/user/admin/update/password/reset/${row.employeeId}`, {}, { loading: true }),
    `重置【${row.loginName}】密码`
  ).then((res) => {
    ElMessageBox({
      message: `新密码为【${res}】`,
    });
  });
  updata();
};
</script>
